package cn.bugstack.infrastructure.adapter.port;

import cn.bugstack.domain.trade.adapter.port.ITradePort;
import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.bugstack.infrastructure.gateway.GroupBuyNotifyService;
import cn.bugstack.infrastructure.redis.IRedisService;
import cn.bugstack.types.enums.NotifyTaskHTTPEnumVO;
import jodd.util.StringUtil;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 代码的路
 * @Date: 2025/3/5 15:32
 * @Param:
 * @Return:
 * @Description:
 **/

@Service
public class TradePort implements ITradePort {


    @Resource
    private GroupBuyNotifyService groupBuyNotifyService;

    @Resource
    private IRedisService redisService;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTaskEntity) {

        RLock lock = redisService.getLock(notifyTaskEntity.getLockKey());
        try {
           if (lock.tryLock(3,0, TimeUnit.SECONDS)){

               try {
                   if (StringUtil.isBlank(notifyTaskEntity.getNotifyUrl())){
                       return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                   }
                   return groupBuyNotifyService.groupBuyNotify(notifyTaskEntity.getNotifyUrl(),notifyTaskEntity.getParameterJSON());
               }finally {
                   if (lock.isLocked() && lock.isHeldByCurrentThread()){
                       lock.unlock();
                   }
               }
           }
           return NotifyTaskHTTPEnumVO.NULL.getCode();

        }catch (Exception e){
           Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }

}
